/*
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.vip.jwt.common.utils.menu;

import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 树形菜单封装
 *
 * @author limk
 * @date 2018-04-11 9:30
 */
public class MenuTreeUtil {

    private List<Menu> nodes;

    public MenuTreeUtil(List<Menu> nodes) {
        this.nodes = nodes;
    }

    public List<Menu> buildTree() {
        List<Menu> list = new ArrayList<Menu>();
        for (Menu node : nodes) {
            if (StrUtil.isEmpty(node.getParentId())) {
                list.add(node);
            }
        }
        list = getSortChilds(list);
        for (Menu node : list) {
            build(node);
        }
        return list;
    }

    /**
     * 构建权限树
     *
     * @param node
     */
    private void build(Menu node) {
        List<Menu> children = getChilds(node);
        if (!children.isEmpty()) {
            node.setChildren(children);
            for (Menu child : children) {
                build(child);
            }
        }
    }

    /**
     * 构建子菜单
     *
     * @param node
     * @return
     */
    private List<Menu> getChilds(Menu node) {
        List<Menu> children = new ArrayList<Menu>();
        String id = node.getId();
        for (Menu child : nodes) {
            if (id.equals(child.getParentId())) {
                children.add(child);
            }
        }
        return getSortChilds(children);
    }

    /**
     * 排序
     *
     * @param childs
     * @return
     */
    private List<Menu> getSortChilds(List<Menu> childs) {
        MyCompare my = new MyCompare();
        Collections.sort(childs, my);
        return childs;
    }

}

